﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Solution145
{
    public IList<int> PostorderTraversal(TreeNode root)
    {
        Stack<TreeNode> stack = new Stack<TreeNode>();

        IList<int> res = new List<int>();
        TreeNode pre = null;

        while (root != null || stack.Count > 0)
        {
            while (root != null)
            {
                stack.Push(root);

                root = root.left;
            }
            root = stack.Pop();

            if (root.right == null || pre == root.right)//右子树空或者遍历过才可以访问根节点
            {
                res.Add(root.val);
                pre = root;
                root = null;
            }
            else
            {
                stack.Push(root);//再次入栈
                root = root.right;
            }
        }
        return res;
    }
}